package API.ObjectAPI;

//作为clone示范的类Information，继承Cloneable接口以支持clone
class InformationOne implements Cloneable{
    private int id;
    private String name;
    private String password;
    private int[] data;


    public InformationOne() {
    }

    public InformationOne(int id, String name, String password, int[] data) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.data = data;
    }

    //将类中data数组属性转换为String类型返回
    private String transferData(){
        StringBuilder dataInfor = new StringBuilder();
        dataInfor.append("[");
        for (int i = 0; i < data.length; i++) {
            dataInfor.append(data[i]);
            if(i < data.length - 1) {
                dataInfor.append(",");
            }
        }
        dataInfor.append("]");
        return dataInfor.toString();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int[] getData() {
        return data;
    }

    public void setData(int index, int data) {
        this.data[index] = data;
    }

    public String toString() {
        return "{id = " + id + ", name = " + name + ", password = " + password + ", data = " + transferData() + "}";
    }

    @Override
    //重写clone方法以提供支持
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

}

public class ShallowClone {
    public static void main(String[] args) {
        //创建实例类对象
        InformationOne informationOne1 = new InformationOne(1, "Jack", "123456", new int[]{1, 2, 3, 4, 5});
        //输出其中内容
        System.out.println(informationOne1);
        //clone information1对象，并输出相关结果
        try {
            InformationOne informationOne2 = (InformationOne) informationOne1.clone();
            System.out.println(informationOne2);
            //此代码实现的是浅克隆，克隆出的对象内部，引用数据类型的属性中记录的地址值和原对象一致
            //原对象修改其值，克隆出的对象对应的值也会修改
            informationOne1.setData(0, 10);
            System.out.println(informationOne2);
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }
}
